import pickle

import orjson
from tortoise.exceptions import DoesNotExist

from common.redis import use_redis
from dao.area import area_dao
from schemas import Response


class AreaService:

    all_city = 'citys'
    cache_time = 60 * 60 * 24 * 7

    @classmethod
    async def get_parents(cls, request):
        # 缓存数据库
        redis = use_redis(request, 2)
        if data := await redis.get(cls.all_city):
            return Response(data=orjson.loads(data))
        # 写入缓存
        data = await area_dao.all_parent()
        await redis.setex(cls.all_city, cls.cache_time, orjson.dumps(data))
        return Response(data=orjson.loads(data))

    @classmethod
    async def get_area(cls, request, pk):
        redis = use_redis(request, 2)
        if data := await redis.get(pk):
            return Response(data=orjson.loads(data))
        try:
            data = await area_dao.all_parent(parent=pk)
            # 写入缓存
            await redis.setex(pk, cls.cache_time, orjson.dumps(data))
            return Response(data=data)
        except DoesNotExist:
            return Response(code=400, errmsg='地区编码错误')
